package com.sukaiyi.leetcode._1115print_foobar_alternately;

import java.util.concurrent.Semaphore;

/**
 * @author sukaiyi
 * @date 2020/06/24
 */
public class FooBar {

    private final Semaphore suppleSemaphore = new Semaphore(0);
    private final Semaphore consumeSemaphore = new Semaphore(1);
    private final int n;

    public FooBar(int n) {
        this.n = n;
    }

    public void foo(Runnable printFoo) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            consumeSemaphore.acquire();
            printFoo.run();
            suppleSemaphore.release();
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            suppleSemaphore.acquire();
            printBar.run();
            consumeSemaphore.release();
        }
    }
}
